﻿<template>
  <a-card :bordered="false">
    <div class="table-operator">
      <a-button v-if="hasPerm('cm_productionitem.Add')" type="primary" icon="plus" @click="handleAdd()">新建</a-button>
      <a-button
        v-if="hasPerm('cm_productionitem.Delete')"
        type="primary"
        icon="minus"
        @click="handleDelete(selectedRowKeys)"
        :disabled="!hasSelected()"
        :loading="loading"
      >删除</a-button>
      <a-button type="primary" icon="redo" @click="getDataList()">刷新</a-button>
      <a-button
        style="margin-left: 8px"
        @click="exportExcel($rootUrl)"
      >
        <a-icon type="download" />
        成本报表
      </a-button>
    </div>

    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="4" :sm="24">
            <a-form-item label="查询类别">
              <a-select v-model="queryParam.condition">
                <a-select-option key="InvCode">存货编号</a-select-option>
                <a-select-option key="InvName">存货名称</a-select-option>
                <a-select-option key="InvStd">存货规格型号</a-select-option>
                <a-select-option key="ProBatch">生产批号</a-select-option>
                <a-select-option key="RawBatch">原料批号</a-select-option>
                <a-select-option key="Supplier">供应商</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-input allowClear @keydown="inputKeyDown" v-model="queryParam.keyword" placeholder="关键字" />
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item label="日期">
              <a-range-picker
                :placeholder="['开始日期', '结束日期']"
                :format="monthFormat"
                v-model:value="iYearMonth"
                :mode="mode"
                @change="onChange"
                v-decorator="['date-picker', ruleconfig]"
              />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-button type="primary" @click="() => {this.pagination.current = 1; this.getDataList()}">查询</a-button>
            <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <a-table
      ref="table"
      :scroll="{ y: tableHight }"
      :columns="columns"
      :rowKey="(row, index) => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'checkbox' }"
      :bordered="true"
      size="small"
      :customRow="loadRow">
      <span slot="InDate" slot-scope="InDate">{{ timeFormat(InDate,'YYYY-MM-DD') }}</span>
      <span slot="OutDate" slot-scope="OutDate">{{ timeFormat(OutDate,'YYYY-MM-DD') }}</span>
      <template slot="OutQty" slot-scope="text">
        <span>{{ text.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) }}</span>
      </template>
      <template slot="InQty" slot-scope="text">
        <span>{{ text.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) }}</span>
      </template>
      <span slot="Loss" slot-scope="Loss">{{ (Loss * 100).toFixed(0) + '%' }}</span>
    </a-table>
    <edit-form ref="editForm" :parentObj="this" @returnMain="handleReturnMain"></edit-form>
  </a-card>
</template>

<script>
import EditForm from './EditForm'
import { download } from '@/components/download'
import moment from 'moment'
const columns = [
  { title: '生产日期', dataIndex: 'InDate', align: 'center', width: '10%', scopedSlots: { customRender: 'InDate' } },
  { title: '存货编号', dataIndex: 'InvCode', align: 'center', width: '10%' },
  { title: '存货名称', dataIndex: 'InvName', align: 'center', width: '10%' },
  { title: '规格型号', dataIndex: 'InvStd', align: 'center', width: '7%' },
  { title: '出库日期', dataIndex: 'OutDate', align: 'center', width: '10%', scopedSlots: { customRender: 'OutDate' } },
  { title: '生产批号', dataIndex: 'ProBatch', align: 'center', width: '10%' },
  { title: '原料批号', dataIndex: 'RawBatch', align: 'center', width: '10%' },
  { title: '供应商', dataIndex: 'Supplier', align: 'center', width: '27%' },
  { title: '原料数量', dataIndex: 'OutQty', align: 'center', width: '8%', scopedSlots: { customRender: 'OutQty' } },
  { title: '原料价格', dataIndex: 'OutPrice', align: 'center', width: '8%' },
  { title: '成品数量', dataIndex: 'InQty', align: 'center', width: '8%', scopedSlots: { customRender: 'InQty' } },
  { title: '加工成本', dataIndex: 'ProcessingCosts', align: 'center', width: '7%' },
  { title: '损耗率', dataIndex: 'Loss', align: 'center', width: '7%', scopedSlots: { customRender: 'Loss' } },
  { title: '成本单价', dataIndex: 'InPrice', align: 'center', width: '8%' }
]

export default {
  components: {
    EditForm
  },
  mounted () {
    this.$nextTick(() => {
      // 页面渲染完成后的回调
      this.tableHight = this.getTableHeight(true) + 24.5
    })
    this.getDataList()
  },
  data () {
    return {
      tableHight: 570, // 表格高度
      data: [],
      pagination: {
        current: 1,
        pageSize: 20,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['20', '30', '40', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      filters: {},
      sorter: { field: 'InDate', order: 'desc' },
      loading: false,
      columns,
      monthFormat: 'yyyy-MM-DD',
      mode: ['date', 'date'],
      iYearMonth: [],
      ruleconfig: {
        rules: [{ type: 'object', required: true, message: '请选择年月!' }]
      },
      queryParam: {},
      selectedRows: [],
      selectedRowKeys: []
    }
  },
  methods: {
    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.sorter = { ...sorter }
      this.getDataList()
    },
    // 导出模板
    exportExcel (rootUrl) {
      const condition = typeof this.queryParam.condition === 'undefined' ? '' : this.queryParam.condition
      const keyword = typeof this.queryParam.keyword === 'undefined' ? '' : this.queryParam.keyword
      const sDate = typeof this.queryParam.sDate === 'undefined' ? '' : this.queryParam.sDate
      const dDate = typeof this.queryParam.dDate === 'undefined' ? '' : this.queryParam.dDate
      const url = rootUrl + '/CostManagement/cm_productionitem/ExportDataToExcel?condition=' + condition + '&keyword=' + keyword + '&sDate=' + sDate + '&dDate=' + dDate
      console.log(url)
      download(url, '成本报表')
    },
    onChange (date, dateString) {
      this.queryParam.sDate = moment(date[0]).format(this.monthFormat)
      this.queryParam.dDate = moment(date[1]).format(this.monthFormat)
    },
    getDataList () {
      this.selectedRowKeys = []
      this.loading = true
      this.$http
        .post('/CostManagement/cm_productionitem/GetSelectDataList', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          Search: this.queryParam,
          ...this.filters
        })
        .then(resJson => {
          this.loading = false
          this.data = resJson.Data
          if (this.data) {
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          }
        })
    },
    inputKeyDown (e) {
      if (e.keyCode === 13) {
        if (!this.queryParam[0].keyword) return this.$message.error('请输入查询条件')
        this.getDataList()
      }
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    hasSelected () {
      return this.selectedRowKeys.length > 0
    },
    handleAdd () {
      this.$refs.editForm.openForm(null, '新建生产成本孙表信息')
    },
    handleEdit (id) {
      this.$refs.editForm.openForm(id, '编辑生产成本孙表信息')
    },
    handleDelete (ids) {
      var thisObj = this
      this.$confirm({
        title: '确认删除吗?',
        onOk () {
          return new Promise((resolve, reject) => {
            thisObj.$http.post('/CostManagement/cm_productionitem/DeleteData', ids).then(resJson => {
              resolve()

              if (resJson.Success) {
                thisObj.$message.success('操作成功!')

                thisObj.getDataList()
              } else {
                thisObj.$message.error(resJson.Msg)
              }
            })
          })
        }
      })
    },
    handleReturnMain () {
      this.getDataList()
    },
    // 表格点击选中取消
    loadRow (record, index) {
      return {
        on: {
          click: () => {
            // 记录为disabled则直接返回，默认为不可选
            if (record.disabled) return
            const type = 'checkbox'
            const key = record.Id
            let selectedRows = this.selectedRows
            let selectedRowKeys = this.selectedRowKeys
            if (type === 'radio') {
              selectedRowKeys = [key]
              selectedRows = [record]
            }
            if (!this.selectedRowKeys.includes(key)) {
              selectedRowKeys.push(key)
              selectedRows.push(record)
            } else {
              const index = this.selectedRowKeys.findIndex(skey => skey === key)
              selectedRows.splice(index, 1)
              selectedRowKeys.splice(index, 1)
            }
            this.updateSelect(selectedRowKeys, selectedRows)
            this.onSelectChange(selectedRowKeys, selectedRows)
          }
        }
      }
    },
    // 更新选中操作
    updateSelect (selectedRowKeys, selectedRows) {
      this.selectedRows = selectedRows
      this.selectedRowKeys = selectedRowKeys
    }
  }
}
</script>
